package com.pivotal.cloud.crypto;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @className: com.pivotal.cloud.security.crypto.Digester
 * @projectName: PivotalCloud项目
 * @module: PivotalCloud项目-Digester类，主要位于Security安全模块-Digester工具类模块
 * @content: Digester-Digester工具类
 * @author: Powered by Marklin
 * @datetime: 2025-06-25 20:58
 * @version: 1.0.0
 * @copyright: Copyright © 2018-2025 PivotalCloud Systems Incorporated. All rights
 * reserved.
 */
public class Digester {

	private final String algorithm;

	private int iterations;

	/**
	 * Create a new Digester.
	 * @param algorithm the digest algorithm; for example, "SHA-1" or "SHA-256".
	 * @param iterations the number of times to apply the digest algorithm to the input
	 */
	public Digester(String algorithm, int iterations) {
		// eagerly validate the algorithm
		createDigest(algorithm);
		this.algorithm = algorithm;
		setIterations(iterations);
	}

	public byte[] digest(byte[] value) {
		MessageDigest messageDigest = createDigest(this.algorithm);
		for (int i = 0; i < this.iterations; i++) {
			value = messageDigest.digest(value);
		}
		return value;
	}

	public void setIterations(int iterations) {
		if (iterations <= 0) {
			throw new IllegalArgumentException("Iterations value must be greater than zero");
		}
		this.iterations = iterations;
	}

	private static MessageDigest createDigest(String algorithm) {
		try {
			return MessageDigest.getInstance(algorithm);
		}
		catch (NoSuchAlgorithmException ex) {
			throw new IllegalStateException("No such hashing algorithm", ex);
		}
	}

}
